﻿using Quartz;
using Quartz.Impl;
using Quartz.Impl.Matchers;
using System.Collections.Specialized;

namespace quartz.net简单封装
{
    public static class TimeWork
    {
        private static NameValueCollection pars = new NameValueCollection
        {
            //scheduler名字
            ["quartz.scheduler.instanceName"] = "_scheduler",
            //线程池个数
            ["quartz.threadPool.threadCount"] = "20",
            //类型为JobStoreXT,事务
            ["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz",
            //JobDataMap中的数据都是字符串
            //["quartz.jobStore.useProperties"] = "true",
            //数据源名称
            ["quartz.jobStore.dataSource"] = "myDS",
            //数据表名前缀
            ["quartz.jobStore.tablePrefix"] = "QRTZ_",
            //使用Sqlserver的Ado操作代理类
            ["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz",
            //数据源连接字符串
            ["quartz.dataSource.myDS.connectionString"] = "Server=.;Database=QuartzDb;Uid=sa;Pwd=12345678;Encrypt=false",
            //数据源的数据库
            ["quartz.dataSource.myDS.provider"] = "SqlServer",
            //序列化类型
            ["quartz.serializer.type"] = "json",//binary
            //自动生成scheduler实例ID，主要为了保证集群中的实例具有唯一标识
            ["quartz.scheduler.instanceId"] = "AUTO",
            //是否配置集群
            ["quartz.jobStore.clustered"] = "true",
            //禁用对数据库模式的验证
            ["quartz.jobStore.performSchemaValidation"]="false"
        };
        ////调度器
        //private static IScheduler _scheduler = new StdSchedulerFactory(pars).GetScheduler().GetAwaiter().GetResult();
        //调度器
        private static IScheduler _scheduler = new StdSchedulerFactory().GetScheduler().GetAwaiter().GetResult();

        public static async Task StartTimeWork(DateTimeOffset time, ActionJob action)
        {
            //触发器
            var trigger = TriggerBuilder.Create().StartAt(time).Build();
            //作业
            var jobDetail = JobBuilder.Create<QuartaJob>()
                .SetJobData(new JobDataMap()
                {
                    new KeyValuePair<string,object>("_Action",action)
                })
                .Build();

            //开启调度
            await _scheduler.Start();
            //添加调度
            await _scheduler.ScheduleJob(jobDetail, trigger);
        }

        /// <summary>
        /// 创建一个指定时间开始，按指定间隔时间轮询执行，永不结束的任务
        /// </summary>
        /// <param name="startTime">开始时间</param>
        /// <param name="pollTime">间隔时间</param>
        /// <param name="action">委托任务</param>
        /// <returns></returns>
        public static async Task CreatePollJob(DateTimeOffset startTime, TimeSpan pollTime, ActionJob action)
        {
            //触发器
            var trigger = TriggerBuilder.Create()
                .WithSimpleSchedule(options =>
                {
                    options.RepeatForever();
                    options.WithInterval(pollTime);
                })
                .StartAt(startTime).Build();
            //作业
            var job = JobBuilder.Create<QuartaJob>()
                .SetJobData(new JobDataMap()
                {
                    new KeyValuePair<string,object>("_Action",action)
                })
                .Build();
            await _scheduler.Start();
            //添加调度
            await _scheduler.ScheduleJob(job, trigger);
        }

        /// <summary>
        /// 获取正在执行的任务列表
        /// </summary>
        /// <returns></returns>
        public static async Task<List<IJobDetail>> GetCurrentExecuteJob()
        {
            var jobs=new List<IJobDetail>();
            var gropus =await _scheduler.GetJobGroupNames();
            foreach(var item in gropus)
            {
                var keys =await _scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(item));
                foreach(var key in keys)
                {
                    var job =await _scheduler.GetJobDetail(key);
                    jobs.Add(job);
                }
            }
            return jobs;
        }
    }
}